<template>
  <base-breadcrumb :title="$route.meta.title" :breadcrumb="!isAudit">
    <a-spin :spinning="pageLoading">
      <!-- 质量验收计划维护 -->
      <base-info ref="baseInfo" isValidate :form="baseForm" :is-need-auth="true" :disabled="disabled || editModel == '0'" :editModel="editModel" @companychange="companychange"></base-info>
      <a-card :bordered="false" style="margin-bottom: 50px">
        <title-name title="质量验收计划表"></title-name>
        <a-button v-if="editModel != 0" :disabled="!baseForm.projectId" @click="handleManage(0)" icon="plus" class="mb12" type="primary">添加计划项</a-button>
        <!-- 表格 -->
        <div v-if="editModel != 0">
          <a-table ref="table" tableLayout="fixed" size="default" bordered rowKey="id" :columns="columns1" :data-source="dataSource1" :pagination="false">
            <span slot="action" slot-scope="text, record, index">
              <template v-if="record.statusCode != 0">
                <a @click="handleManage(1, record)" type="primary">编辑</a>
                <a-divider type="vertical" />
                <a @click="handleDelete(index)" type="primary">删除</a>
              </template>
            </span>
          </a-table>
        </div>
        <div v-else-if="baseForm.itemsMap && Object.keys(baseForm.itemsMap).length > 0" style="padding: 0 20px;">
          <service-export-mould
            class="ml12"
            :isButton="true"
            :serviceiUrl="qualityApiUrl"
            buttonType="default"
            :requestParams="{ id: id,  historyId: historyId}"
            url="/quality/acceptance-plan/excel"
            buttonText="全部导出"
          ></service-export-mould>
          <div style="margin: 20px; margin-right: 0;" v-for="(val, key) in baseForm.itemsMap" :key="key">
            <title-name :title="key"></title-name>
            <a-table ref="tableItemsMap" tableLayout="fixed" size="default" bordered rowKey="id" :columns="columns2" :data-source="val" :pagination="false">
              <span slot="action" slot-scope="text, record, index">
                <template v-if="!!record.recordStatusName || !!record.acceptanceRecordStatusName">
                  <a @click="handleOpenRecord(record)" type="primary">查看验收记录</a>
                </template>
              </span>
            </a-table>
          </div>
        </div>
      </a-card>
    </a-spin>
    
    <!-- 页脚操作栏 -->
    <div v-if="!isConsultation" class="btn_box page-btn-right-top">
      <a-button :disabled="loading[0] || loading[1]" v-if="editModel == 1 && statusCode === '0' && form.version && form.version <= 1" type="danger" class="button_right" @click="handleRemove">删除草稿</a-button>
      <a-button :loading="loading[0]" :disabled="loading[1]" v-if="(editModel == 1 && (statusCode === '0' || statusCode === '3')) || editModel == 2 || editModel == 3" type="primary" class="button_right" @click="handleSubmit(0)">{{
        statusCode === '2' || statusCode === '3' ? '保存' : '保存草稿'
      }}</a-button>
      <a-button
        :loading="loading[1]"
        :disabled="loading[0]"
        v-if="(editModel == 1 && (statusCode === '0' || statusCode === '3')) || editModel == 2 || (editModel != 0 && statusCode === '2')"
        type="primary"
        class="button_right"
        @click="handleSubmit(1)"
        >提交</a-button
      >
      <a-button v-if="checkVisibleInDetail" type="primary" @click="handleActiveClose">关闭</a-button>
    </div>
    <DialogForm
      ref="dialogForm"
      :visible.sync="visible"
      editModel="E"
      :form="form"
      :headerTitle="['质量验收计划添加', '质量验收计划修改'][editModelTwo]"
      :width="1000"
      :formList="formList"
      :confirmBtn="['提交', '保存'][editModelTwo]"
      @select="handleSelect"
      @change="handleChange"
      @getOptions="handleGetOptions"
      @blur="handleInput"
      @confirm="handleConfirm"
    />
  <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import { qualityApiUrl } from '@/api/config.js'
import { acceptancePlan } from '@/api/quality/quality' // api
import ServiceExportMould from '@/components/ServiceExportMould'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import DialogForm from '@/components/DialogForm' // 表单弹窗
import SelectPersonByProject from '@/components/Select/SelectPersonByProject'
import SelectTreeSubItem from '@/components/Select/SelectTreeSubItem' // 分部分项
import SelectTreeWbs from './SelectTreeWbs' // wbs
import Selector from '@/components/Select/Selector'
import BaseInfo from '@/components/businessComponents/BaseInfo' // 基础信息
import SelectProjectType from '@/components/Select/SelectProjectType' // 工程类别
import { HandleProportion } from '@/api/complaint'
export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    DialogForm,
    BaseInfo,
    ServiceExportMould
  },
  props: {
    // 是否作为审批详情
    isAudit: {
      type: Boolean,
      default: false
    },
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      qualityApiUrl,
      baseForm: {},
      visible: false,
      exportLoading: false,
      // 查询参数
      queryParam: {},
      dataSource1: [],
      statusCode: '', // 审批状态
      pageLoading: false,
      loading: { 0: false, 1: false },
      id: '', // 业务id
      historyId: '',
      editModel: '0', // 页面操作类型
      editModelTwo: '0', // 表格操作类型
      form: {}, // 弹窗表单
      disabled: false,
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  computed: {
    columns1() {
      let columns = [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          align: 'center',
          customRender(text, record, index) {
            return index + 1
          }
        },
        {
          title: '验收类型',
          dataIndex: 'checkAcceptanceTypeCode.label',
          ellipsis: true
        },
        {
          title: '验收内容',
          dataIndex: 'unitEngineering',
          ellipsis: true
        },
        {
          title: '分部分项',
          dataIndex: 'subItemId.label',
          ellipsis: true
        },
        {
          title: 'WBS项',
          dataIndex: 'wbsId.label',
          ellipsis: true
        },
        {
          title: '验收负责人',
          dataIndex: 'acceptorId.label',
          ellipsis: true
        },
        {
          title: '计划验收时间',
          dataIndex: 'acceptanceDate',
          ellipsis: true
        },
        {
          title: '验收部位',
          dataIndex: 'part',
          ellipsis: true
        },
        {
          title: '备注',
          dataIndex: 'remarks',
          ellipsis: true
        },
        {
          title: '操作',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ]
      return columns
    },
    columns2() {
      let columns = [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          align: 'center',
          customRender(text, record, index) {
            return index + 1
          }
        },
        {
          title: '验收类型',
          dataIndex: 'checkAcceptanceTypeName',
          ellipsis: true
        },
        {
          title: '验收内容',
          dataIndex: 'unitEngineering',
          ellipsis: true
        },
        {
          title: '分部分项',
          dataIndex: 'subItemName',
          ellipsis: true
        },
        {
          title: 'WBS项',
          dataIndex: 'wbsName',
          ellipsis: true
        },
        {
          title: '验收负责人',
          dataIndex: 'acceptorName',
          ellipsis: true
        },
        {
          title: '计划验收时间',
          dataIndex: 'acceptanceDate',
          ellipsis: true
        },
        {
          title: '验收部位',
          dataIndex: 'part',
          ellipsis: true
        },
        {
          title: '预验收结果',
          dataIndex: 'acceptanceRecordStatusName',
          ellipsis: true
        },
        {
          title: '验收结果',
          dataIndex: 'recordStatusName',
          ellipsis: true
        },
        {
          title: '备注',
          dataIndex: 'remarks',
          ellipsis: true
        },
        {
          title: '操作',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ]
      return columns
    },
    // 表单列表
    formList() {
      return [
        // code 1 分部分项验收
        // code 2 阶段验收
        // code 3 专项验收
        // code 4 竣工验收
        // code 0 单位工程验收
        {
          type: Selector,
          keyName: 'checkAcceptanceTypeCode',
          label: '验收类型',
          span: 12,
          attrs: {
            labelInValue: true,
            selectType: '23',
            valueName: 'code'
          },
          rule: {
            required: true,
            message: '请选择验收类型', 
            trigger: 'change'
          }
        },
        {
          type: 'a-input',
          keyName: 'unitEngineering',
          span: 12,
          label: '验收内容',
          rule: {
            required: true,
            message: '请输入验收内容', 
            trigger: 'change'
          },
        },
        {
          keyName: 'projectConstructionTypeId',
          label: '工程类别',
          type: SelectProjectType, 
          hidden: this.$refs.dialogForm?.forms?.checkAcceptanceTypeCode?.key !== '1',
          attrs:{
            showStop:false,
            id: this.baseForm.projectId,
          },
          rule: {
            required: true,
            message: '请选择工程类别', 
            trigger: 'change'
          },
          span: 12
        },
        {
          type: SelectTreeSubItem,
          hidden: this.$refs.dialogForm?.forms?.checkAcceptanceTypeCode?.key !== '1',
          keyName: 'subItemId',
          span: 12,
          label: '分部分项',
          attrs: {
            projectId: (this.baseForm.projectId && this.$refs.dialogForm?.forms?.projectConstructionTypeId) ? this.baseForm.projectId : '',
            typeId: (this.baseForm.projectId && this.$refs.dialogForm?.forms?.projectConstructionTypeId) ? this.$refs.dialogForm?.forms?.projectConstructionTypeId : '',
            init: false,
            labelInValue: true
          },
          rule: {
            required: true,
            message: '请选择分部分项', 
            trigger: 'change'
          },
        },
        {
          type: SelectTreeWbs,
          keyName: 'wbsId',
          hidden: this.$refs.dialogForm?.forms?.checkAcceptanceTypeCode?.key === '4',
          span: 12,
          label: 'WBS',
          attrs: {
            projectId: this.baseForm.projectId,
            labelInValue: true
          },
          rule: {
            required: true,
            message: '请选择WBS', 
            trigger: 'change'
          },
        },
        {
          type: SelectPersonByProject,
          keyName: 'acceptorId',
          label: '验收负责人',
          span: 12,
          attrs: {
            showSearch: true,
            projectId: this.baseForm.projectId,
            labelInValue: true
          },
          rule: {
            required: true,
            message: '请选择验收负责人', 
            trigger: 'change'
          },
        },
        {
          type: 'a-input',
          keyName: 'part',
          hidden: this.$refs.dialogForm?.forms?.checkAcceptanceTypeCode?.key === '4',
          span: 12,
          label: '验收部位'
        },
        {
          type: 'a-input-number',
          keyName: 'acceptanceNum',
          span: 12,
          disabled: !this.$refs.dialogForm?.forms.wbsId,
          hidden: this.$refs.dialogForm?.forms?.checkAcceptanceTypeCode?.key === '4',
          label: '验收时间（WBS节点完成后天数）',
          attrs: {
            max: 10000000
          },
          rule: {
            required: true,
            message: '请输入验收时间（WB节点完成后天数）', 
            trigger: 'change'
          },
        },
        // a-date-picker disabled 切换 rule 好像无效
        this.$refs.dialogForm?.forms?.checkAcceptanceTypeCode?.key === '4' ? {
          type: 'a-date-picker',
          keyName: 'acceptanceDate4',
          placeholder: '请选择',
          label: '计划验收时间',
          span: 12,
          attrs: {
            valueFormat: 'YYYY-MM-DD',
          },
          rule: {
            required: true,
            message: '请选择计划验收时间', 
            trigger: 'change'
          },
        } : {
          type: 'a-date-picker',
          keyName: 'acceptanceDate0',
          placeholder: '请选择',
          disabled: true,
          label: '计划验收时间',
          span: 12,
          attrs: {
            valueFormat: 'YYYY-MM-DD',
          },
        },
        {
            keyName: 'remarks',
            type: 'BaseTextarea',
            label: '备注',
            attrs: {
                maxLength: 3000
            },
            span: 24
        },
      ]
    }
  },
  async mounted() {
    this.$route.meta.title = ['质量验收计划查看', '质量验收计划编辑', '质量验收计划新增', '质量验收计划更新'][this.editModel]
      //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('quality_check_plan')
    this.id = this.$route.query.id
    this.getDetail()
  },
  methods: {
    getDetail() {
      if (!this.id) {
        return false
      }
      let args = {}
      if (this.businessId) {
        args.businessId = this.businessId
      } else {
        args.id = this.id
      }
      if (this.historyId) {
        args.historyId = this.historyId
      }
      this.pageLoading = true
      return acceptancePlan.getDetail(args).then((res) => {
        if (res.data) {
          let data = res.data.acceptancePlanItems ? res.data.acceptancePlanItems : []
          if (data?.length > 0) {
            // 禁用表单
            this.disabled = true
            // 格式化列表
            data.forEach((item) => {
              item.acceptorId = {
                key: item.acceptorId,
                label: item.acceptorName
              }
              item.wbsId = {
                value: item.wbsId,
                label: item.wbsName
              }
              item.checkAcceptanceTypeCode = {
                key: item.checkAcceptanceTypeCode,
                label: item.checkAcceptanceTypeName
              }
              item.subItemId &&
                (item.subItemId = {
                  value: item.subItemId,
                  label: item.subItemName
                })
            })
          }
          this.statusCode = res.data.statusCode // 映射审批状态
          this.baseForm = res.data // 映射表单
          this.dataSource1 = data
        }
      }).finally(() => {
          this.pageLoading = false
        })
    },
    handleOpenRecord(record) {
      let typeCode = ''
      let name = ''
      let query = {
        editModel: 0,
      }
      if (record) {
        query.detailId = record.detailId
        typeCode = record.checkAcceptanceTypeCode
      }
      if (typeCode === '1') {
        // 分部分项
        name = '/quality/receivanceManagement/receivanceRecord/acceptanceSubItemEdit'
      } else if (typeCode === '4') {
        // 竣工验收
        name = '/quality/receivanceManagement/receivanceRecord/acceptanceCompletionEdit'
      } else {
        // 单位工程/阶段验收/专项验收
        name = '/quality/receivanceManagement/receivanceRecord/acceptanceSpecialEdit'
      }
      this.$router.push({
        name,
        query
      })
    },
    companychange(branchCompanyId) {
      this.baseForm.branchCompanyId = branchCompanyId
    },
    /**
     * 监听wbs
     */
    handleSelect(name, value, vnode) {
      if (name === 'wbsId') {
        // 设置WBS节点结束时间
        this.wbsEndTime = vnode.dataRef.planEndTime
        if (this.$refs.dialogForm?.forms.acceptanceNum) {
          this.$set(this.$refs.dialogForm?.forms, 'acceptanceDate0', this.$dateFormat(new Date(this.$refs.dialogForm?.forms.acceptanceNum * 3600 * 24 * 1000 + Number(new Date(this.wbsEndTime))), 'D'))
        }
      } else if (name === 'projectConstructionTypeId') {
        this.$set(this.$refs.dialogForm.forms, 'subItemId', null)  // 清空分部分项
      }
    },
    handleGetOptions(name, list) {
      if (name === 'projectConstructionTypeId') {
        if (!this.$refs.dialogForm?.forms.projectConstructionTypeId && list && list.length > 0) {
          this.$set(this.$refs.dialogForm.forms, 'projectConstructionTypeId', list[0].projectTypeId)  // 工程类别 获取第一个
        }
      }
      
    },
    /**
     * 监听验收类型重置分部分项value
     */
    handleChange(name, value) {
      if (name === 'checkAcceptanceTypeCode' && value && value.key === '0') {
        if (Object.keys(this.$refs.dialogForm?.forms?.subItemId || {})?.length > 0) {
          this.$refs.dialogForm.forms.subItemId = null
        } else {
          this.$set(this.$refs.dialogForm.forms, 'subItemId', null)
        }
      }
    },
    /**
     * 监听天数更新验收时间
     */
    handleInput(name, e) {
      if (name === 'acceptanceNum') {
        let value = e?.target?.value
        // 计算验收时间(WBS节点结束时间加上天数)
        if (value || value == 0) {
          this.$set(this.$refs.dialogForm?.forms, 'acceptanceDate0', this.$dateFormat(new Date((value || 0) * 3600 * 24 * 1000 + Number(new Date(this.wbsEndTime))), 'D'))
        }
      }
    },
    /**
     * 表格添加和编辑
     */
    handleManage(a, e) {
      this.editModelTwo = a
      if (e) {
        if (e?.checkAcceptanceTypeCode?.key === '4') {
          e.acceptanceDate4 = e?.acceptanceDate || ''
        } else {
          e.acceptanceDate0 = e?.acceptanceDate || ''
        }
      }
      if (e?.acceptanceNum && e?.acceptanceDate) {
        this.wbsEndTime = this.$dateFormat(new Date(Number(new Date(e.acceptanceDate)) - e.acceptanceNum * 3600 * 24 * 1000), 'D')
      }
      this.form = e || {}
      this.visible = true
    },
    /**
     * 表格删除
     */
    handleDelete(index) {
      this.$confirm({
        title: '温馨提示',
        content: '确认删除?',
        onOk: () => {
          this.dataSource1.splice(index, 1)
          this.dataSource1.length === 0 && (this.disabled = false)
        }
      })
    },
    /**
     * 表格添加和编辑
     */
    handleConfirm(e) {
      let form = this.$clone(e)
      form.acceptanceDate = form.acceptanceDate4 || form.acceptanceDate0 || ''
      if (form.acceptanceDate4) {
        delete form.acceptanceDate4
      }
      if (form.acceptanceDate0) {
        delete form.acceptanceDate0
      }
      if (this.editModelTwo == 0) {
        form.id = 'add_' + this.dataSource1.length
        this.dataSource1.length === 0 && (this.disabled = true)
        this.dataSource1.unshift(form)
      } else {
        this.dataSource1.forEach((item, index) => {
          if (e.id === item.id) {
            this.$set(this.dataSource1, index, form)
          }
        })
      }
      this.visible = false
    },
    /**
     * 删除草稿
     */
    handleRemove() {
      this.$confirm({
        title: '温馨提示',
        content: '确定删除草稿？',
        onOk: () => {
          return acceptancePlan.remove({ id: this.id }).then((res) => {
            this.$message.success('删除成功！')
            // 关闭当前页
            this.$multiTab.close()
          })
          // .catch((res) => {
          //   this.$message.warning('删除失败！')
          // })
        }
      })
    },
    /**
     * 提交表单
     */
    handleSubmit(e) {
      this.setProcessConfig = null;
      let acceptancePlanItems = this.dataSource1.map((item) => {
        let obj = Object.assign({}, item, {
          checkAcceptanceTypeCode: item.checkAcceptanceTypeCode?.key,
          acceptorId: item.acceptorId?.key,
          subItemId: item.subItemId?.value,
          wbsId: item.wbsId?.value
        })
        if (obj.id?.indexOf('add_') !== -1) {
          delete obj.id
        }
        return obj
      })
      // 校验项目信息
      this.$refs.baseInfo.validate().then(() => {
        if (acceptancePlanItems.length > 0 || e === 0) {
          let name = ['update', 'create', 'adjustment'][this.editModel - 1] // 动态取得api请求方法
          let form = {
            acceptancePlanItems: acceptancePlanItems,
            projectId: this.baseForm.projectId,
            branchCompanyId: this.baseForm.branchCompanyId,
            statusCode: this.statusCode == '3' && e == 0 ? this.statusCode : e
          }
          // 若为编辑则添加id
          if (this.editModel == 1 || this.editModel == 3) {
            form.id = this.id
          }
          // 加载框
          this.loading[e] = true
          this.submitApprovalConfirm(e==1?this.processConfig: 6, (flag)=>{
            if(!flag) {
              this.loading[e] = false
              return
            }
            acceptancePlan[name](form)
            .then((res) => {
              // 取消加载框
              this.loading[e] = false
              this.$message.success(['保存', '提交', '更新'][e] + '成功！')
              if(e*1===1) {
                //提交时，返回id
                this.businessId = res.data.businessId;
                this.setProcessConfig = this.processConfig;
                return
              }else{
                this.$multiTab.close()
              }
            })
            .catch((res) => {
              // this.$message.warning(['保存', '提交', '更新'][e] + '失败！')
              // 取消加载框
              this.loading[e] = false
            })
          })

        } else {
          this.$message.warning('计划表不能为空')
        }
      })
    }
  }
}
</script>
